package com.ecommerce.service;

import com.ecommerce.dao.CartDAO;
import com.ecommerce.dao.OrderDAO;
import com.ecommerce.dao.ProductDAO;
import com.ecommerce.model.CartItem;
import com.ecommerce.model.Order;
import com.ecommerce.model.OrderItem;
import com.ecommerce.model.Product;
import com.ecommerce.util.InputUtil;
import java.util.ArrayList;
import java.util.List;

public class OrderService {
    private OrderDAO orderDAO;
    private CartDAO cartDAO;
    private ProductDAO productDAO;
    private CartService cartService;

    public OrderService() {
        this.orderDAO = new OrderDAO();
        this.cartDAO = new CartDAO();
        this.productDAO = new ProductDAO();
        this.cartService = new CartService();
    }

    public boolean createOrderFromCart(int userId) {
        System.out.println("\n=== 创建订单 ===");

        // 检查购物车是否为空
        List<CartItem> cartItems = cartDAO.getCartItemsByUserId(userId);
        if (cartItems.isEmpty()) {
            System.out.println("购物车为空，无法创建订单！");
            return false;
        }

        // 显示购物车内容
        cartService.viewCart(userId);

        // 获取收货地址
        String shippingAddress = InputUtil.getStringInput("请输入收货地址: ");

        // 计算总金额
        double totalAmount = cartService.calculateCartTotal(userId);

        // 确认创建订单
        String confirm = InputUtil.getStringInput("确认创建订单？(y/N): ");
        if (!"y".equalsIgnoreCase(confirm)) {
            System.out.println("取消创建订单");
            return false;
        }

        // 检查库存
        for (CartItem cartItem : cartItems) {
            Product product = productDAO.getActiveProductById(cartItem.getProductId());
            if (product == null) {
                System.out.println("商品 '" + cartItem.getProductName() + "' 已下架！");
                return false;
            }
            if (product.getStockQuantity() < cartItem.getQuantity()) {
                System.out.println("商品 '" + product.getName() + "' 库存不足！当前库存: " + product.getStockQuantity());
                return false;
            }
        }

        // 创建订单
        Order order = new Order(userId, totalAmount, shippingAddress);
        List<OrderItem> orderItems = new ArrayList<>();

        for (CartItem cartItem : cartItems) {
            OrderItem orderItem = new OrderItem();
            orderItem.setProductId(cartItem.getProductId());
            orderItem.setQuantity(cartItem.getQuantity());
            orderItem.setUnitPrice(cartItem.getProductPrice());
            orderItem.setSubtotal(cartItem.getSubtotal());
            orderItems.add(orderItem);
        }

        // 保存订单
        boolean success = orderDAO.createOrder(order, orderItems);

        if (success) {
            System.out.println("订单创建成功！订单号: " + order.getOrderNumber());
            System.out.printf("订单金额: ¥%.2f\n", totalAmount);

            // 清空购物车
            cartDAO.clearUserCart(userId);

            // 更新库存
            updateProductStock(orderItems);

            return true;
        } else {
            System.out.println("订单创建失败！");
            return false;
        }
    }

    private void updateProductStock(List<OrderItem> orderItems) {
        // 按产品ID分组，减少数据库操作
        for (OrderItem item : orderItems) {
            Product product = productDAO.getProductById(item.getProductId());
            if (product != null) {
                int newStock = product.getStockQuantity() - item.getQuantity();
                // 使用销售类型记录库存变更
                productDAO.updateProductStock(item.getProductId(), newStock, "sale",
                        "订单销售", 0); // 0表示系统操作
            }
        }
    }

    public void viewUserOrders(int userId) {
        List<Order> orders = orderDAO.getOrdersByUserId(userId);

        System.out.println("\n=== 我的订单 ===");
        if (orders.isEmpty()) {
            System.out.println("暂无订单");
        } else {
            for (Order order : orders) {
                System.out.println("ID: " + order.getId() + " | " + order);
            }
        }
        System.out.println("===============");
    }

    public void viewAllOrders() {
        List<Order> orders = orderDAO.getAllOrders();

        System.out.println("\n=== 所有订单 ===");
        if (orders.isEmpty()) {
            System.out.println("暂无订单");
        } else {
            for (Order order : orders) {
                System.out.println("ID: " + order.getId() + " | " + order);
            }
        }
        System.out.println("===============");
    }

    public void viewOrderDetails(int orderId, int userId, boolean isAdmin) {
        Order order = orderDAO.getOrderById(orderId);
        if (order == null) {
            System.out.println("订单不存在！");
            return;
        }

        // 检查权限：用户只能查看自己的订单，管理员可以查看所有订单
        if (!isAdmin && order.getUserId() != userId) {
            System.out.println("无权查看此订单！");
            return;
        }

        List<OrderItem> orderItems = orderDAO.getOrderItemsByOrderId(orderId);

        System.out.println("\n=== 订单详情 ===");
        System.out.println(order.toDetailedString());
        System.out.println("\n订单商品:");
        if (orderItems.isEmpty()) {
            System.out.println("无商品");
        } else {
            for (OrderItem item : orderItems) {
                System.out.println("  " + item);
            }
        }
        System.out.println("===============");
    }

    public void cancelOrder(int userId) {
        System.out.println("\n=== 取消订单 ===");
        viewUserOrders(userId);

        int orderId = InputUtil.getIntInput("请输入要取消的订单ID: ");

        // 验证订单属于当前用户
        Order order = orderDAO.getOrderById(orderId);
        if (order == null || order.getUserId() != userId) {
            System.out.println("订单不存在或无权操作！");
            return;
        }

        if (!"pending".equals(order.getStatus())) {
            System.out.println("只能取消待确认的订单！当前状态: " + order.getStatusText());
            return;
        }

        String confirm = InputUtil.getStringInput("确认取消订单？(y/N): ");
        if ("y".equalsIgnoreCase(confirm)) {
            boolean success = orderDAO.cancelOrder(orderId);
            if (success) {
                System.out.println("订单取消成功！");

                // 恢复库存
                restoreProductStock(orderId);
            } else {
                System.out.println("订单取消失败！");
            }
        } else {
            System.out.println("取消操作");
        }
    }

    private void restoreProductStock(int orderId) {
        List<OrderItem> orderItems = orderDAO.getOrderItemsByOrderId(orderId);
        for (OrderItem item : orderItems) {
            Product product = productDAO.getProductById(item.getProductId());
            if (product != null) {
                int newStock = product.getStockQuantity() + item.getQuantity();
                // 使用退货类型记录库存变更
                productDAO.updateProductStock(item.getProductId(), newStock, "return",
                        "订单取消恢复库存", 0); // 0表示系统操作
            }
        }
    }

    public void updateOrderStatus() {
        System.out.println("\n=== 更新订单状态 ===");
        viewAllOrders();

        int orderId = InputUtil.getIntInput("请输入订单ID: ");

        System.out.println("选择新状态:");
        System.out.println("1. 待确认");
        System.out.println("2. 已确认");
        System.out.println("3. 已发货");
        System.out.println("4. 已送达");
        System.out.println("5. 已取消");

        int choice = InputUtil.getIntInput("请选择: ");
        String status;
        switch (choice) {
            case 1: status = "pending"; break;
            case 2: status = "confirmed"; break;
            case 3: status = "shipped"; break;
            case 4: status = "delivered"; break;
            case 5: status = "cancelled"; break;
            default:
                System.out.println("无效选择！");
                return;
        }

        boolean success = orderDAO.updateOrderStatus(orderId, status);
        if (success) {
            System.out.println("订单状态更新成功！");

            // 如果取消订单，恢复库存
            if ("cancelled".equals(status)) {
                restoreProductStock(orderId);
            }
        } else {
            System.out.println("订单状态更新失败！");
        }
    }

    public void manageCustomerOrders(int userId) {
        while (true) {
            System.out.println("\n=== 订单管理 ===");
            System.out.println("1. 查看我的订单");
            System.out.println("2. 查看订单详情");
            System.out.println("3. 创建订单");
            System.out.println("4. 取消订单");
            System.out.println("5. 返回上级菜单");

            int choice = InputUtil.getIntInput("请选择操作: ");

            switch (choice) {
                case 1:
                    viewUserOrders(userId);
                    break;
                case 2:
                    int orderId = InputUtil.getIntInput("请输入订单ID: ");
                    viewOrderDetails(orderId, userId, false);
                    break;
                case 3:
                    createOrderFromCart(userId);
                    break;
                case 4:
                    cancelOrder(userId);
                    break;
                case 5:
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    public void manageAdminOrders() {
        while (true) {
            System.out.println("\n=== 订单管理 ===");
            System.out.println("1. 查看所有订单");
            System.out.println("2. 查看订单详情");
            System.out.println("3. 更新订单状态");
            System.out.println("4. 返回上级菜单");

            int choice = InputUtil.getIntInput("请选择操作: ");

            switch (choice) {
                case 1:
                    viewAllOrders();
                    break;
                case 2:
                    int orderId = InputUtil.getIntInput("请输入订单ID: ");
                    viewOrderDetails(orderId, 0, true);
                    break;
                case 3:
                    updateOrderStatus();
                    break;
                case 4:
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }
}
